# FILE: GeoCodingBroker.py
# DESC: obtains geo coding for LSAEntry object using google geo coder 
#
import urllib

from web.service.WebServiceBroker import WebServiceBroker
#from infra.logging import logger

#TODO: move to oreus.conf

GOOGLE_GEO_CODER_URL="http://maps.google.com/maps/geo?output=json&oe=utf-8&mapclient=jsapi&q=%s&key=ABQIAAAA_0hAzy4dbwijHMCZEOJ-XBStNkmczT10EsTokrjT4KAT0QQIgxRZl68X5OJEjvGyV5yLIMrI2fp0DA"
G_GEO_SUCCESS = 200



class GeoCodingBroker(WebServiceBroker):

	def geoCode(self, street, streetNum, city):
		#log = logger.getLogger()
		lat = None
		lng = None
		accuracy = None 
		
		if streetNum:
			address = '%s %s,%s' % (street, streetNum, city)
		else:
			address = '%s,%s' % (street, city)
		
		#log.debug('Geocoding address "%s"...' % address)
				
		try:		
			response = self.requestJSON(GOOGLE_GEO_CODER_URL % urllib.quote_plus(address.encode('utf-8')))
			if response and response['Status']['code'] == G_GEO_SUCCESS and response['Placemark']:
				placemark = response['Placemark'][0]									
				lat = placemark['Point']['coordinates'][1]
				lng = placemark['Point']['coordinates'][0]
				accuracy = placemark['AddressDetails']['Accuracy']				
				#log.debug('Done (accuracy = %s)' % accuracy)						
		except Exception, e:
			raise e
			#log.error(u'Failed to geocode address "%s", reason = %e' % (address, e))
			
		return (lat, lng, accuracy)